package com.kfm.servlet.day03;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Random;
import java.util.UUID;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    private static final String BASE_PATH = "D:\\temp\\upload\\";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 获取上传文件
        Part part = req.getPart("img");

        if (part != null){
            // 获取上传文件的类型
            String contentType = part.getContentType();
            // 限制上传文件的类型
            if (!contentType.startsWith("image/")){
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write("<h1>上传失败, 请上传图片</h1>");
                return;
            }

            // 获取文件大小
            long size = part.getSize();
            if (size > 1024 * 1024){
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write("<h1>上传失败, 请上传小于1M的图片</h1>");
                return;
            }


            String name = part.getSubmittedFileName();
            System.out.println(name);
            // 解决文件名重复问题
            name = UUID.randomUUID() + name;
            // 文件分类: 按照时间分类 2020/01/01/xxx.jpg
            LocalDate now = LocalDate.now();
            String datePath = "" + now.getYear() + File.separator + now.getMonthValue() + File.separator + now.getDayOfMonth() ;
            File dir = new File(BASE_PATH, datePath);
            if (!dir.exists()){
                dir.mkdirs();
            }

            part.write(dir + File.separator + name);

            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("<h1>上传成功</h1>");
            resp.getWriter().write("<a href=\"down?name=" + name + "\">下载</a>");
        }
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
        // uuid
        System.out.println(UUID.randomUUID());
   }
}
